import router from '@/router/index'
import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useUserStore = defineStore('user', () => {
  const appid = ref(window.localStorage.getItem('appid') || '')
  const platform = ref(4)
  const userInfo = ref(JSON.parse(window.localStorage.getItem('userInfo')) || {
    uuid: '',
    name: '',
    avatar: '',
  })
  const token = ref(window.localStorage.getItem('token') || '')
  const setUserInfo = (val) => {
    userInfo.value = val
  }

  const setAppid = (val) => {
    appid.value = val
  }

  const getLoginState = () => {
    return  token.value !== ''
  }

  const setToken = (val) => {
    token.value = val
  }

  const ResetUserInfo = (value = {}) => {
    userInfo.value = {
      ...userInfo.value,
      ...value
    }
  }
  /* 获取用户信息*/
  const GetUserInfo = async() => {
    const res = await getUserInfo()
    if (res.code === 0) {
      setUserInfo(res.data.userInfo)
    }
    return res
  }
  /* 登出*/
  const LoginOut = async() => {
    // const res = await jsonInBlacklist()
    // if (res.code === 0) {
      token.value = ''
      // appid.value = '',
      // sessionStorage.clear()
      // localStorage.clear()
      userInfo.value = {
        uuid: '',
        name: '',
        avatar: '',
      }
      router.push({ name: 'login' })
      window.location.reload()
    // }
  }
  /* 清理数据 */
  const ClearStorage = async() => {
    token.value = ''
    sessionStorage.clear()
    localStorage.clear()
  }
  watch(() => token.value, () => {
    window.localStorage.setItem('token', token.value)
  })

  watch(() => appid.value,() => {
    window.localStorage.setItem('appid', appid.value)
  })

  watch(() => userInfo.value,() => {
    window.localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  })

  return {
    userInfo,
    token,
    GetUserInfo,
    ResetUserInfo,
    LoginOut,
    setToken,
    ClearStorage,
    setAppid,
    appid,
    platform,
    getLoginState
  }
})
